<?php
namespace app\api\controller;
use app\common\controller\Base;
use jwt\Jwt;
class Login extends Base{
	/**
	 * 接口登录
	 * @param  string $name 登录名
	 * @param  string $pwd  登录密码
	 * @param  string $imei 设备识别码（UDID）
	 * @param  string $code 验证码
	 * @return json
	 */
    function login($name='',$pwd='',$imei='',$code=''){
    	//if(request()->isPost()){
	    	$validate=$this->validate([
	    		'name'=>$name,
	    		'pwd'=>$pwd,
	    		'imei'=>$imei,
	    		//'code'=>$code,
	    	],[
	    		'name|'.lang('User name')=>'require',
	    		'pwd|'.lang('User password')=>'require',
	    		'imei|UDID'=>'require',
	    		//'code|'.lang('Verification code')=>'require|captcha',
	    	]);
	    	if(true!==$validate)return json($validate,1);
            $field='id,login_name,login_pwd,name,head_img,tel,wxmsg_interval,wxmsg_task_id';
	    	$rs=model('member')->read(['login_name'=>$name],$field);
	    	if($rs&&$rs['login_pwd']===encrypt_pwd($pwd)){ //登录成功
	    		$has=model('device')->read(['member_id'=>$rs['id'],'udid'=>$imei],'id');
	    		if(empty($has)){
	    			return json('设备不存在',1);
	    		}
	    		unset($rs['login_pwd']);
                $rs['_loginTime']=time();
                $rs['device_id']=$has['id'];
                $rs['head_img']=images($rs['head_img']);
                $t=Jwt::encode($rs);
                $rs['token']=$t['data'];
	    		return json(lang('Login was successful'),0,$rs);
	    	}
	    	return json(lang('Incorrect username or password'),1);
    	//}
    }
    function register(){
    	//if(request()->isPost()){
	    	$data=$this->request->param();
	    	$validate=$this->validate([
	    		'name'=>$data['login_name'],
	    		'pwd'=>$data['login_pwd'],
	    	],[
	    		'name|'.lang('User name')=>'require',
	    		'pwd|'.lang('User password')=>'require',
	    	]);
	    	if(true!==$validate)return json($validate,1);

	    	$data['s_time']=time();
	    	$data['login_pwd']=encrypt_pwd($data['login_pwd']);

	    	$rs=model($this->table)->add($data);
	    	if(isset($rs['id'])){
	    		return json(lang('Register was successful'),0,$rs);
	    	}
	    	return json(lang('The system is busy'),1);
    	//}
    }
}
